/*******************************************************************************
 * Copyright 2007, 2009 InnovaSoft SA http://www.innovasoft.biz/
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package biz.innovasoft.ndb.index;

import java.io.Serializable;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.Configuration;
import net.sf.ehcache.store.MemoryStoreEvictionPolicy;
import biz.innovasoft.ndb.RepositoryConfiguration;

public class TemporalIndexCache implements Serializable {

	private static final long serialVersionUID = -7797912785807858623L;
	
	private CacheManager cManager;
	private Cache cache;
	
	public TemporalIndexCache() {
		this(RepositoryConfiguration.DEFAULT_TIME_TO_LIVE, RepositoryConfiguration.DEFAULT_IDLE_TIME);
	}
	
	public TemporalIndexCache (long liveTime, long idleTime) {
		Configuration config = new Configuration();
		CacheConfiguration cacheConfig = new CacheConfiguration();
		cacheConfig.setEternal(false);
		cacheConfig.setDiskPersistent(false);
		cacheConfig.setTimeToIdleSeconds(10);
		cacheConfig.setTimeToLiveSeconds(10);
		cacheConfig.setMemoryStoreEvictionPolicyFromObject(MemoryStoreEvictionPolicy.FIFO);
		cacheConfig.setName("default");
		config.addDefaultCache(cacheConfig);
		this.cManager = new CacheManager ( config );
		this.cache = new Cache ("default", 200, false, false, 10, 10);
		cManager.addCache(cache);
	}

	public void addIndexManager(IndexManager manager) {
		Element elem = new Element (manager.getName(), manager);
		cache.put(elem, false);
	}
	
	public IndexManager getIndexManager(String name) {
		Element elem = cache.get(name);
		if ( elem != null ) {
			return (IndexManager)elem.getValue();
		}
		return null;
	}

	public boolean containsIndexForClass(String name) {
		return cache.isElementInMemory(name);
	}
	
}
